<template>
  <div>
    <cus-modal ref="modal" title="导入" width="520" @onOk="onOk" @on-visible-change="visibleChange">
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="120">
        <FormItem label="采购时间">
          <el-date-picker type="week" format="yyyy 第 WW 周" placeholder="选择周" v-model="form.dateTime"
            @change="dateWeekChange" transfer :picker-options="{ firstDayOfWeek: 1 }"
            style="width: 280px; z-index: 9999 !important; position: relative">
          </el-date-picker>
        </FormItem>
        <FormItem label="采购计划名称" prop="purchasingPlanName" :rules="{
          required: true,
          message: '采购计划名称不能为空',
          trigger: 'change',
        }">
          <Input v-model="form.purchasingPlanName" clearable style="width: 280px" placeholder="选择采购时间自动生成"></Input>
        </FormItem>
        <FormItem label="选择文件" prop="fileName" :rules="{
          required: true,
          message: '文件不能为空',
          trigger: 'change',
        }">
          <Upload ref="upload" :before-upload="beforeUpload" action="" multiple type="select">
            <Button icon="ios-cloud-upload-outline" style="
                width: 280px;
                height: 40px;
                display: flex;
                justify-content: left;
                align-items: center;
                overflow: hidden;
              ">{{ form.fileName || "上传文件" }}</Button>
          </Upload>
        </FormItem>
      </Form>
    </cus-modal>
    <!--导入错误提示-->
    <excelErrorModal ref="excelErrorModal"></excelErrorModal>
    <Spin size="large" fix v-if="loading"></Spin>
  </div>
</template>

<script>
import {
  postApiPurchasingThisWeekIsExistInPortPurchasingExcel,
  postApiPurchasingInportPurchasingPlanExcel
} from "@/api/business/manager";
import excelErrorModal from './excelErrorModal.vue';
export default {
  components: { excelErrorModal },
  name: "importExcel",
  data() {
    return {
      loading: false,
      ruleValidate: {},
      form: {
        startDate: "", //导入采购需求开始时间
        stopDate: "", //导入采购需求结束时间
        dateTime: "", // 采购时间
        purchasingPlanName: "", // 采购计划名称
        fileName: "", // 上传文件名称
        file: null, //导入采购需求文件
      }
    };
  },
  mounted() { },
  methods: {
    visibleChange(val) {
      if (!val) {
        this.form = {
          startDate: "", //导入采购需求开始时间
          stopDate: "", //导入采购需求结束时间
          dateTime: "", // 采购时间
          purchasingPlanName: "", // 采购计划名称
          fileName: "", // 上传文件名称
          file: null, //导入采购需求文件
        }
        this.$refs.formValidate.resetFields();
        console.log(this.form);
      }
    },
    show() {
      this.$refs["modal"].show = true;
    },
    //导入采购需求时间选择事件
    dateWeekChange(time) {
      this.form.startDate = this.getCurrentWeek(time)[0];
      this.form.stopDate = this.getCurrentWeek(time)[6];
      this.form.purchasingPlanName =
        this.getCurrentWeek(time)[0].substring(5) +
        " - " +
        this.getCurrentWeek(time)[6].substring(5) +
        "号采购计划";
    },
    //导入采购需求Excel文件上传前事件
    beforeUpload(file) {
      this.form.file = file;
      this.form.fileName = file.name;
      return;
    },
    onOk() {
      this.$refs["formValidate"].validate((valid) => {
        if (valid) {
          this.postApiPurchasingThisWeekIsExistInPortPurchasingExcelApi();
        }
      });
    },
    // 获取本周日期组件处理
    getCurrentWeek(date) {
      let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
      let currentDay = nowData.getDay();
      if (currentDay == 0) {
        currentDay = 7;
      }
      let beforweek = [],
        afterWeek = [];
      for (let i = 1; i <= 7; i++) {
        if (currentDay - i >= 0) {
          let DayTime =
            nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000;
          beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        } else {
          let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
          afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        }
      }
      afterWeek = afterWeek.reverse();
      let dateList = [...beforweek, ...afterWeek];
      return dateList;
    },
    //导入采购单Excel文件前效验时间段内是否已导入采购需求------------接口
    postApiPurchasingThisWeekIsExistInPortPurchasingExcelApi() {
      this.$cu.showLoading();
      return new Promise((resolve) => {
        let params = {
          purchasingPlanName: this.form.purchasingPlanName, //采购计划名称
          startDate: this.form.startDate, //采购计划k开始时间
          stopDate: this.form.stopDate, //采购计划k结束时间
        };
        postApiPurchasingThisWeekIsExistInPortPurchasingExcel(params).then(
          (res) => {
            if (res.retCode == 2000) {
              this.postApiPurchasingInportPurchasingPlanExcelApi();
              resolve();
            } else {
              this.$cu.hideLoading(1.5);
            }
          }
        );
      });
    },
    //导入采购单Excel文件----------------------------接口
    postApiPurchasingInportPurchasingPlanExcelApi() {
      return new Promise((resolve) => {
        let params = new FormData();
        for (const key in this.form) {
          params.append(key, this.form[key]);
        }
        postApiPurchasingInportPurchasingPlanExcel(params).then((res) => {
          if (res.retCode == 2000) {
            this.$cu.hideLoading(1.5);
            this.$Message.success(res.retMsg);
            this.$parent.onInit();
            this.$refs["modal"].show = false;
            this.$emit('onCancel')
            console.log("开始关闭")
            resolve();
          } else {
            this.$cu.hideLoading(0.5);
            this.$refs['excelErrorModal'].show();
            this.$refs['excelErrorModal'].data = res.data;
          }
        });
      });
    },
  },
};
</script>

<style scoped></style>

